package LeetCode;

import java.util.Arrays;

public class KMP {
    public static void main(String[] args) {
//        for (int sad : kmpNext("leeto")) {
//            System.out.println(sad);
//        }
        System.out.println(kmp());
    }

    static int[] kmpNext(String dest) {
        int[] next = new int[dest.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < dest.length(); i++) {
            while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];
            }
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    static int kmp() {
        String s1 = "sedbutsad";
        String s2 = "sade";
        char[] arr1 = s1.toCharArray();
        char[] arr2 = s2.toCharArray();
        int i = 0;
        int j = 0;
        int[] next = kmpNext(s2);
        while (i < arr1.length) {
            if (arr1[i] == arr2[j]) {
                if (j == arr2.length - 1) {
                    return i - j;
                }
                i++;
                j++;
            } else {
                // 前j-1都匹配，所有回退next(j-1)
                if (j == 0) {
                    i = i + 1;
                } else {
                    i = i - next[j - 1];
                }
                j = 0;
            }
        }
        return -1;

    }


}
